package com.lpf.xypermission.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PermissionUtil {

    public static boolean verifyPermissions(int... grants) {
        if (grants.length == 0) return false;

        for (int grant : grants) {
            if (grant != PackageManager.PERMISSION_GRANTED) return false;
        }

        return true;
    }

    public static boolean shouldShowRequestPermissionRationales(Activity context, String... permissions) {

        for (String permission : permissions) {

            if (context.shouldShowRequestPermissionRationale(permission)) return true;

        }

        return false;


    }


    public static boolean hasSelfPermissions(Context context, String... permissions) {

        for (String permission : permissions) {
            if (!hasSelfPermission(context, permission)) {
                return false;
            }
        }

        return true;

    }


    private static boolean hasSelfPermission(Context context, String permission) {
        return ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }


    public static void invokeAnnotation(Object object, Class annotationclass, int requestcode) {

        Class<?> aClass = object.getClass();
        Method[] methods = aClass.getMethods();

        if (methods.length == 0) return;

        for (Method method : methods) {

            boolean isannotationPresent = method.isAnnotationPresent(annotationclass);
            if (isannotationPresent) {

                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length != 1) {
                    throw new RuntimeException("只能有一个参数");
                }

                method.setAccessible(true);

                try {
                    method.invoke(object,requestcode);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }


            }


        }


    }


}
